package com.study.command;

import java.util.concurrent.Future;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.study.dao.entity.MovieUser;

import rx.Observable;
/**
 * 通过继承的方式来实现command
 * 注：只能调用一次
 *
 */
@Service
public class UserCommand extends HystrixCommand<MovieUser>{
	
	@Autowired
	RestTemplate restTemplate;
	
	public UserCommand() {
		super(HystrixCommandGroupKey.Factory.asKey("group")); //必须
	}

	//重写fallback方法
	@Override
	protected MovieUser getFallback() {
		//获取导致降级的异常
		Throwable executionException = getExecutionException();
		System.out.println("********************: exception : " + executionException );
		return super.getFallback();
	}

	@Override
	protected MovieUser run() throws Exception {
		MovieUser movieUser = restTemplate.getForObject("http://sunxj-microservice-provider-user/simple/1", MovieUser.class);
		return movieUser;
	}

	
	public static void main(String[] args) throws Exception {
		UserCommand command = new UserCommand();
		
		//方式1:同步执行
		MovieUser execute = command.execute();
		//方式2:异步执行
		Future<MovieUser> queue = command.queue();
		MovieUser movieUser = queue.get();
		//方式3：响应式执行，hot-observable，命令会立即执行
		Observable<MovieUser> observe = command.observe();
		//方式4：响应式执行，cold-observable，命令不会立即执行
		Observable<MovieUser> observable = command.toObservable();
	}
}
